/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.cezary.butler.walili.client.mime;

import pl.cezary.butler.walili.client.mime.MimeTypeAction;
import pl.cezary.butler.walili.client.mime.IMimeTypeHandler;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Czarek
 */
public class MimeTypeHandler implements IMimeTypeHandler {

    private Map<String, MimeTypeAction> map;

    public MimeTypeHandler() {
        this(new HashMap<String, MimeTypeAction>());
    }

    public MimeTypeHandler(Map<String, MimeTypeAction> map) {
        this.map = map;
    }
    
    public static MimeTypeHandler getHandlerForMap(Map<String, MimeTypeAction> map){
        return new MimeTypeHandler(map);
    }  

    @Override
    public void registerAction(final String mimeType, MimeTypeAction action) {
        map.put(mimeType, action);
    }

    @Override
    public boolean handleMimeType(String mimeType, URLConnection connection) {
        MimeTypeAction action = map.get(mimeType.toLowerCase().trim());
        if (action != null) {
            return action.process(connection);
        } else {
            final String[] split = mimeType.split("/");
            action = map.get(split[0]);
            if(action!=null){
                return action.process(connection);
            }
        }
        return true;
    }
}
